package com.frank.yinyuetai.Fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.frank.yinyuetai.Adapter.MVRecycleViewAdapter;
import com.frank.yinyuetai.Bean.MVListBean;
import com.frank.yinyuetai.Bean.VideoBean;
import com.frank.yinyuetai.R;
import com.frank.yinyuetai.Util.URLProviderUtil;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/8/18 0018.
 */
public class MvBaseFragment extends Fragment {
    @Bind(R.id.mv_RecyclerView)
    RecyclerView mvRecyclerView;
    @Bind(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.fab_mv)
    FloatingActionButton floatingButton;
    private int position;
    private String code;
    private List<VideoBean> mList;
    protected int mWidth;
    protected int mHeight;
    private int lastVisibleItem;
    private int offset, size = 20;
    private MVRecycleViewAdapter viewAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.mv_base_fragment, null);
        position = getArguments().getInt("position");
        switch (position) {
            case 0:
                code = "FS";
                break;
            case 1:
                code = "KR";
                break;
            case 2:
                code = "US";
                break;
            case 3:
                code = "JP";
                break;
            case 4:
                code = "ML";
                break;
            case 5:
                code = "HT";
                break;
            case 6:
                code = "ELITE";
                break;
        }
        Log.i("FHJKLHLKJH", position + "");
        ButterKnife.bind(this, view);
        mList = new ArrayList<>();
        viewAdapter = new MVRecycleViewAdapter(mList, MvBaseFragment.this.getActivity());
        mvRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mvRecyclerView.setAdapter(viewAdapter);

        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                requestData(true);
            }
        }, 100);

        floatingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mvRecyclerView.smoothScrollToPosition(0);
            }
        });
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        swipeRefreshLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, getResources()
                        .getDisplayMetrics()));
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestData(true);
            }
        });
        observerView(360, 640);

        return view;
    }

    private void requestData(boolean isFirst) {
        if (isFirst) {
            offset = 0;
        } else {
            offset = offset + 20;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils.getInstance()
                        .get(URLProviderUtil.getMVListUrl(code, offset, size))
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                Gson gson = new Gson();
                                MVListBean mListBean = gson.fromJson(s, MVListBean.class);
                                List<VideoBean> vList = mListBean.getVideos();
                                mList.addAll(vList);
                                Message message = new Message();
                                message.what = 1;
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onAfter(@Nullable String s, @Nullable Exception e) {
                                super.onAfter(s, e);
                                swipeRefreshLayout.setRefreshing(false);
                            }


                        });
            }
        }).start();

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    viewAdapter.notifyDataSetChanged();
                    mvRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
                        @Override
                        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                            super.onScrollStateChanged(recyclerView, newState);
                            if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == viewAdapter.getItemCount()) {
                                swipeRefreshLayout.setRefreshing(true);
                                requestData(false);
                            }
                        }

                        @Override
                        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                            super.onScrolled(recyclerView, dx, dy);
                            lastVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
                        }
                    });
                    break;
            }
        }
    };

    public static MvBaseFragment newInstance(int position) {
        MvBaseFragment baseFragment = new MvBaseFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        baseFragment.setArguments(bundle);
        return baseFragment;
    }

    protected void observerView(int imgHeight, int imgWidth) {
        DisplayMetrics metric = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        mWidth = metric.widthPixels;
        mHeight = (mWidth * imgHeight) / imgWidth;
    }
}
